<template>
    <div>
        <el-dialog
            :title="options.row.id ? '编辑图标' : '新增图标'"
            :visible.sync="options.visible"
            width="480px"
            custom-class="icon-dialog"
            ref="dialog"
            destroy-on-close
            :before-close="handleClose">
                <el-form :model="form" ref="form" id="form" label-position="right" label-width="94px" size="small" :rules="rules">
                    <el-form-item label="所属程序" prop="app_class">
                        <el-select v-model="form.app_class" placeholder="请选择">
                            <el-option
                              v-for="item in appClassType"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="所属页面" prop="page_class_id">
                        <el-select v-model="form.page_class_id" placeholder="请选择">
                            <el-option
                              v-for="item in pageArr"
                              :key="item.id"
                              :label="item.title"
                              :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="图标名称" prop="category_name">
                        <el-input type="text" placeholder="请输入图片名称" class="input" maxlength="40" autocomplete="off" v-model="form.category_name"></el-input>
                    </el-form-item>
                    <el-form-item label="链接地址" prop="jump_path">
                        <el-input type="text" placeholder="请输入点击图标的跳转地址" class="input" maxlength="80" autocomplete="off" v-model="form.jump_path"></el-input>
                    </el-form-item>
                    <el-form-item label="是否跳转" prop="is_jump">
                        <el-select v-model="form.is_jump" placeholder="请选择">
                            <el-option
                                v-for="item in jumpType"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="关联小程序" prop="app_id" v-if="parseInt(form.is_jump) === 1">
                        <el-select v-model="form.app_id" placeholder="请选择">
                            <el-option
                                v-for="item in appIdType"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="图标图片" class="item_upload" prop="image_path">
                        <el-upload
                            class="upload-box"
                            action="#"
                            list-type="picture-card"
                            :file-list="file_list"
                            :on-remove="handleRemove"
                            :auto-upload="false"
                            :limit="imageLimit"
                            :accept="imageAccept.join(',')"
                            :multiple="false"
                            :on-change="handleChange"
                            :class="{'upload-box': true, 'hideUpload': !!form.image_path}"
                            ref="upload">
                            <i class="el-icon-plus"></i>
                            <div class="el-upload__tip" slot="tip">
                                只支持png格式，透明图片<br>尺寸：100 * 100 (px)
                            </div>
                        </el-upload>
                    </el-form-item>
                    <!-- <el-form-item label="是否展示">
                        <el-switch
                          v-model="form.is_show"
                          size="small"
                          active-color="#13ce66">
                        </el-switch>
                    </el-form-item> -->
                </el-form>
                <template #footer>
                    <el-button size="small" @click="closeDialog">取 消</el-button>
                    <el-button size="small"
                        type="primary"
                        @click="submitForm('form')"
                        :loading="loading">
                        {{ loading ? "提交中 ..." : "确 定" }}
                    </el-button>
                </template>
        </el-dialog>
    </div>
</template>
<script>
export default {
    props: {
        options: {
            type: Object,
            default: () => ({
                row: {}
            })
        }
    },
    data() {
        return {
            imageAccept: ['image/png'],
            imageSzie: 2,
            imageLimit: 1,
            uploadDisplay: false,
            file_list: [],
            form: {
                app_class: "",
                page_class_id: "",
                category_name: "",
                jump_path: "",
                image_path: null,
                is_jump: '0',
                app_id: ''
            },
            loading: false,
            appClassType: [
                {label: '元通汽车小程序', value: '1'},
                {label: '特选好物购', value: '2'},
                {label: '元通APP', value: '3'}
            ],
            jumpType: [
                {label: '不跳转', value: '0'}, 
                {label: '跳转', value: '1'}
            ],
            appIdType: [
                {label: '元通汽车', value: 'wxe863334de4765087'},
                {label: '特惠好物购', value: 'wxd9c1a2604904086a'},
                {label: '新车团购', value: 'wxbccb2ad82bb890f0'},
                {label: '售后团购', value: 'wx6ba19c1cbd39ffd5'},
                {label: 'IM聊天', value: 'wxfda138b7ee0a78c3'}
            ],
            pageArr: [],
            rules: {
                app_class: [
                    { required: true, message: '请选择所属程序', trigger: 'change' }
                ],
                page_class_id: [
                    { required: true, message: '请选择所属页面', trigger: 'change' }
                ],
                category_name: [
                    { required: true, message: '请输入图标名称', trigger: ['blur','change'] }
                ],
                jump_path: [
                    { required: true, message: '请输入链接地址', trigger: ['blur','change'] }
                ],
                is_jump: [
                    { required: true, message: '请选择是否跳转', trigger: ['blur','change'] }
                ],
                app_id: [
                    { required: true, message: '请选择关联的小程序', trigger: ['blur','change'] }
                ],
                image_path: [
                    { required: true, message: '请上传图标图片', trigger: 'change' }
                ],
                // sort: [
                //     { required: true, message: '请输入排序字段', trigger: 'blur' }
                // ]
            },
        }
    },
    created() {
        // 获取所属页面分类
        this.$http.get("/admin/pageIcon/index.php?act=icon&op=pageClassList").then(res => {
            if (res.code === 1) {
                this.pageArr = res.data
            }
        }).catch(error => this.$message.error(error))
    },
    methods: {
        async handleRemove(file, fileList) {
            if(fileList.length < 1) {
                this.form.image_path = ""; // 删除头像，则清空头像部分路径后端检测到icon为空则表示删除头像
            }
            this.form.file_list = fileList
            this.uploadDisplay = fileList.length >= this.imageLimit;
        },
        handleChange(file, fileList) {
            const isValid = this.imageAccept.indexOf(file.raw.type);
            const isLt2M = file.size / 1024 / 1024 < 2;
            this.uploadDisplay = fileList.length >= this.imageLimit
            if (isValid < 0) {
                this.$message.error('图标仅支持 '+this.imageAccept.join(", ").replace(/image\//g, "")+' 格式!');
                return false;
            }
            if (!isLt2M) {
                this.$message.error('图标大小不能超过 2MB!');
                return false;
            }
            let formData = new FormData();
            formData.append("icon_pic", fileList[0].raw)
            this.$http.post('/admin/pageIcon/index.php?act=icon&op=uploadPic', formData).then(res => {
                if (res.code == 1) {
                    this.form = {...this.form, image_path: res.data.img_path }
                }
            }).catch(error => console.log(error))
            this.$refs.form.clearValidate("image_path"); // 移除file_list校验结果
        },
        handleClose(done) {
            this.$confirm('确定要关闭表单吗？')
            .then(() => this.closeDialog())
            .catch()
        },
        closeDialog() {
            if(this.loading) return; // 正在提交数据则禁止关闭窗口
            this.loading = false;
            this.$refs.form.resetFields();
            this.$refs.upload.clearFiles();
            this.form.image_path = null;
            this.$emit("closeDialog");
        },
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    this.loading = true;
                    const formData = {
                        id: this.form.id,
                        app_class: this.form.app_class,
                        page_class_id: this.form.page_class_id,
                        category_name: this.form.category_name,
                        jump_path: this.form.jump_path,
                        image_path: this.form.image_path,
                        jump_state: this.form.is_jump,
                        app_id: parseInt(this.form.is_jump) > 0 ? this.form.app_id : ''
                    }
                    this.$http.post('/admin/pageIcon/index.php?act=icon&op=saveIcon', formData).
                    then(res => {
                        this.loading = false;
                        if(res.code == 1) {
                            this.closeDialog();
                            this.$message.success(res.msg)
                            this.$emit("getData");
                        } else {
                            this.$message.error(res.msg)
                        }
                    }).catch(res => {
                        this.loading = false;
                        this.$message.error(res.msg)
                    })
                } else {
                    return false;
                }
            });
        },
        getDetail(id) {
            return this.$http.post('/admin/pageIcon/index.php?act=icon&op=detail', { id })
        }
	},
	watch: {
        "options.row": {
            immediate: true,
            handler: function(val, oldVal) {
                if (val && val.id) {
                    this.getDetail(val.id).then(res => {
                        this.form = res.data
                        this.file_list = [{url: res.data.image_path_show}]
                    })
                } else {
                    this.form = val
                    this.form.is_jump = "0"
                    this.file_list = []
                }
            }
        }
    }
}
</script>
<style lang="scss">
    .icon-dialog .el-dialog__body {
    padding: 20px 20px 10px;
}
</style>
<style lang="scss" scoped>
.el-form{ 
    padding: 0px 20px;
    .el-select {
        width: 100%;
    }
    /deep/.item_upload {
      .el-form-item__label {
        display: block;
      }
    }
    .upload-box, .el-upload__tip{
      display: flex;
      justify-content: flex-start;
    }
    /deep/.upload-box {
      align-items: top;
      padding-bottom: 0;
      &.hideUpload .el-upload{
        display: none;
      }
      .el-upload {
        flex-shrink: 0;
        line-height: 100px;
        width: 100px;
        height: 100px;
      }
      .el-upload__tip {
        align-items: center;
        padding-left:16px;
        margin: 0px;
        line-height: 180%;
      }
      .el-upload-list--picture-card {
          padding: 0;
          line-height: 100%;
          .el-upload-list__item {
            width: 100px;
            height: 100px;
            margin: 0;
          }
      }
    }
}
</style>
